#!/usr/local/bin/perl
# Yen-Ming Lee <leeym@leeym.com>
use WWW::Mechanize;
use Data::Dumper;
use FindBin qw($Script);
use strict;

my $user = shift;
my $pass = shift;
my $host = shift;

die "usage: $Script [username] [password] [hostname]\n" if !$host;

my $mech = new WWW::Mechanize(
  stack_depth => 0,
  autocheck   => 1,
);
$mech->agent_alias('Windows IE 6');

my $site = 'http://corenetworks.net/';
$mech->get($site);
$mech->submit_form(
  form_number => 1,
  fields      => {
    login_username => $user,
    login_password => $pass,
  }
);
die "$Script: ID/PW incorrect\n" if $mech->content !~ m{Logged in as $user};

my $control = 'https://corenetworks.net/control';
$mech->get("$control/indicator.php?" . time());

my $html = $mech->content;
my $reboot;
foreach my $row ($html =~ m{(<tr.*?</tr>)}sig)
{
  next if $row !~ m{reboot}i;
  my $target = $1 if $row =~ m{ - (\S+)};
  next if ($target ne $host);
  $reboot = "$control/$1" if $row =~ m{(reboot.php\?ID=\d+)};
}
die "$Script: $host not found\n" if !$reboot;
$mech->get($reboot);
$mech->submit_form(form_number => 1, button => 'yes');
